package com.block.sms.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.mapper.SmsConfigInfoMapper;
import com.block.sms.enums.UseTypeEnum;
import com.block.sms.service.ISmsConfigInfoService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * 
 * @since 2021-02-16
 */
@Service
public class SmsConfigInfoServiceImpl extends ServiceImpl<SmsConfigInfoMapper, SmsConfigInfo> implements ISmsConfigInfoService {

    @Resource
    private RedisTemplate<String, SmsConfigInfo> redisSmsConfigInfoTemplate;

    private  static  final  String SMSCONFIG_KEY_PREFIX="SMSCONFIG:USETYPE:{}:{}";
    private  static  final  Long SMSCONFIG_KEY_TIME_OUT=4L;

    /**
     * 获取可用的短信配置(根据使用的类型)
     * @param useTypeEnum
     * @return
     */
    @Override
    public SmsConfigInfo getAbleInfoByUseTypeAndPlatform(UseTypeEnum useTypeEnum, String platform) {
        // 查询redis 缓存配置
        String redisKey = StrUtil.format(SMSCONFIG_KEY_PREFIX, useTypeEnum.getValue(), platform);
        SmsConfigInfo smsConfigInfo= redisSmsConfigInfoTemplate.opsForValue().get(redisKey);
        if(ObjectUtil.isEmpty(smsConfigInfo)){
//            smsConfigInfo = this.baseMapper.getDefaultByUseType(useTypeEnum.getValue(), platform);
            if(smsConfigInfo!=null) {
                redisSmsConfigInfoTemplate.opsForValue().set(redisKey, smsConfigInfo, SMSCONFIG_KEY_TIME_OUT, TimeUnit.HOURS);
            }
        }
        return smsConfigInfo;
    }
}
